package fr.sedoo.sssdata.server.sos.request;

import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.CharEncoding;

public class SosRequest {
	
	private String request;
	private String url;
	private String response;
	
	public boolean execute() throws Exception
	{
		if (request == null)
		{
			throw new Exception("Request is null");
		}
		
		if (url == null)
		{
			throw new Exception("Url is null");
		}
		
		HttpClient httpclient= new HttpClient();
		PostMethod post = new PostMethod(url);

		try {

			String postData = addXmlHeader(request);
			post.setRequestEntity(new StringRequestEntity(postData,"application/xml", CharEncoding.UTF_8));

			int result = httpclient.executeMethod(post);
			
			if (result == HttpStatus.SC_OK)
			{
				InputStream responseBodyAsStream = post.getResponseBodyAsStream();
				StringWriter writer = new StringWriter();
				IOUtils.copy(responseBodyAsStream, writer, CharEncoding.UTF_8);
				String rawXml = writer.toString().trim();
				boolean isValid = validate(rawXml);
				if (isValid == false)
				{
					throw new Exception(rawXml);
				}
				setResponse(rawXml);
			}
			else
			{
				throw new Exception("Wrong return code : "+result);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}

		return true;
	}

	protected boolean validate(String rawXml) 
	{
		if (rawXml.indexOf("ExceptionReport")>0)
		{
			return false;
		}
		return true;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getRequest() {
		return request;
	}

	public void setRequest(String request) {
		this.request = request;
	}

	public String getResponse() {
		return response;
	}

	public void setResponse(String response) {
		this.response = response;
	}
	
	private static String addXmlHeader(String xmlContent)
	{
		if (xmlContent.startsWith("<?xml") == false)
		{
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+xmlContent;
		}
		else
		{
			return xmlContent;
		}
	}

}
